﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace Web_Demo
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                show_treeview();
            }
            //lbUser.Text = HttpContext.Current.Session[constants.user.FIRST_NAME].ToString();
            //if (int.Parse(HttpContext.Current.Session[constants.user.ID_ROLE_USER].ToString()) != 1)
            //{
            //    Menu1.Items[3].Enabled = false;

            //}
        }

        dataconnect da = new dataconnect();
        //private void show_CbbNode()
        //{            
        //    string sql = "SELECT * FROM DMS_Folder";
        //    DataTable dt = da.executeDataTable(sql);            
        //    cbb_Node.DataSource = dt;
        //    cbb_Node.DataTextField = dt.Columns[1].ToString();
        //    cbb_Node.DataValueField = dt.Columns[0].ToString();
        //    cbb_Node.DataBind();
        //}
        private void show_doc(int a)
        {
            lb_status.Visible = false;
            string sql = "SELECT * FROM [DMS_Document] INNER JOIN DMS_Folder_Doc ON DMS_Document.ID_Doc = DMS_Folder_Doc.ID_Doc WHERE ID_Folder = " + a;
            DataTable dt = da.executeDataTable(sql);
            //DMSdataDataContext dms = new DMSdataDataContext();
            //var datable = from p in dms.DMS_Folder_Docs
            //         where p.ID_Folder == a
            //         select p;
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            Response.Write("<script>alert('" + lb.CommandName + "')</script>");
        }

        protected void TreeFolder_TreeNodeEdited(object sender, Obout.Ajax.UI.TreeView.NodeEditingEventArgs e)
        {
            string nameNode = e.NewValue;
            string sql = "UPDATE [DMS_Folder] SET [Name_Folder] = '" + e.NewValue + "' WHERE ID_Folder = " + e.Node.Value;
            da.executeNonQuery(sql);
            lb_status.Text = "Oke!!! Folder " + e.Node.Text + " rename to " + e.NewValue;
        }
        private void show_treeview()
        {
            string sql = "SELECT * FROM DMS_Folder";
            DataTable dt = da.executeDataTable(sql);
            TreeView1.Nodes.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["ID_ParentFolder"] + "" == "")
                {
                    Obout.Ajax.UI.TreeView.Node tnParent = new Obout.Ajax.UI.TreeView.Node();
                    tnParent.Text = dr["Name_Folder"].ToString();
                    tnParent.Value = dr["ID_Folder"].ToString();
                    string value = dr["ID_Folder"].ToString();
                    TreeView1.Nodes.Add(tnParent);
                    FillChild(tnParent, value);
                }
            }
            TreeView1.ExpandAll();
        }

        public int FillChild(Obout.Ajax.UI.TreeView.Node parent, string IID)
        {
            string sql = "SELECT * FROM DMS_Folder WHERE ID_ParentFolder =" + IID;
            DataSet ds = da.executeDataSet(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    Obout.Ajax.UI.TreeView.Node child = new Obout.Ajax.UI.TreeView.Node();
                    child.Text = dr["Name_Folder"].ToString().Trim();
                    child.Value = dr["ID_Folder"].ToString();
                    string temp = dr["ID_Folder"].ToString();
                    parent.ChildNodes.Add(child);
                    FillChild(child, temp);
                }
                return 0;
            }
            else
            {
                return 0;
            }
        }
        protected void TreeFolder_TreeNodeDataBound(object sender, Obout.Ajax.UI.TreeView.NodeEventArgs e)
        {
            System.Data.DataRowView dv = (e.Node.DataItem as System.Data.DataRowView);
            if (dv != null)
            {
                e.Node.Text = String.Format("{0}", dv["Name_Folder"].ToString());
            }
        }

        protected void btn_Add_Click(object sender, EventArgs e)
        {
            //int intNode = int.Parse(Tree1.SelectedNode.Value);            
            if (txt_Node.Text == "")
            {
                Response.Write("<script>alert('Name Folder not null')</script>");
            }
            else if (Label1.Text == "")
            {
                string sql1 = "INSERT INTO [DMS_Folder]([Name_Folder]) VALUES"
                            + "('" + txt_Node.Text + "')";
                da.executeNonQuery(sql1);
                lb_status.Visible = true;
                lb_status.Text = "Insert folder " + txt_Node.Text + " successful!!!";
            }
            else
            {
                string sql = "INSERT INTO [DMS_Folder]([Name_Folder],[ID_ParentFolder]) VALUES"
                              + "('" + txt_Node.Text + "'"
                              + "," + Label1.Text + ")";
                da.executeNonQuery(sql);
                lb_status.Visible = true;
                lb_status.Text = "Insert folder " + txt_Node.Text + " successful!!!";
            }
            show_treeview();
            txt_Node.Text = "";
        }


        protected void btn_Delete_Click(object sender, EventArgs e)
        {
            if (Label1.Text == "")
            {
                Response.Write("<script>alert('Chua chon folder can xoa')</script>");
            }
            else
            {
                //int intnode = int.Parse(Label1.Text);
                //int intnode = int.Parse(TreeView1.SelectedNode.Value);
                string sql = "DELETE FROM DMS_Folder WHERE ID_Folder = " + TreeView1.SelectedNode.Value;
                object a = da.executeNonQuery(sql);
                lb_status.Visible = true;
                lb_status.Text = "Delete Folder thành công!!!!!!!!";
                show_treeview();
            }
            txt_Node.Text = "";
        }
        protected void btn_Rename_Click(object sender, EventArgs e)
        {
            string sql = "UPDATE [DMS_Folder] SET [Name_Folder] = '" + txt_Node.Text + "' WHERE ID_Folder = " + Label1.Text;
            da.executeNonQuery(sql);
            lb_status.Visible = true;
            lb_status.Text = "Rename thành công!!!!!!!!";
            show_treeview();
            txt_Node.Text = "";
        }

        protected void TreeView1_SelectedTreeNodeChanged(object sender, Obout.Ajax.UI.TreeView.NodeEventArgs e)
        {
            lb_status.Visible = false;
            Label1.Text = TreeView1.SelectedNode.Value;
            int a = int.Parse(TreeView1.SelectedNode.Value);
            folder = int.Parse(TreeView1.SelectedNode.Value);
            show_doc(a);
        }

        protected void btn_Upload_Click(object sender, EventArgs e)
        {
            if (Label1.Text == "")
            {
                Response.Write("<script>alert('Chua chon folder can upload file')</script>");
            }
            else if (FileUpload1.FileName == "")
            {
                Response.Write("<script>alert('Chua chon file can upload file')</script>");
            }
            else if (FileUpload1.FileName != "")
            {

                string filePath = Server.MapPath(@"/Document/" + FileUpload1.FileName);
                FileUpload1.PostedFile.SaveAs(filePath);
                string name_Doc = FileUpload1.FileName;
                int size_Doc = FileUpload1.PostedFile.ContentLength;
                string type_Doc = FileUpload1.PostedFile.ContentType;
                // string sqldoc = "INSERT INTO [DMS_Document] ([Name_Doc],[Doc]) VALUES ('" + name_Doc + "','" + Doc_Doc + "')";
                DMSdataDataContext dms = new DMSdataDataContext();
                DMS_Document dms_doc = new DMS_Document();
                dms_doc.Name_Doc = name_Doc;
                dms_doc.Doc = filePath;
                dms_doc.Size = size_Doc;
                dms_doc.Extension = type_Doc;
                DMS_Folder_Doc dms_fd = new DMS_Folder_Doc();
                dms_fd.ID_Folder = int.Parse(Label1.Text);

                dms_doc.DMS_Folder_Docs.Add(dms_fd);
                dms.DMS_Documents.InsertOnSubmit(dms_doc);
                dms.SubmitChanges();
                show_doc(int.Parse(Label1.Text));
                lb_status.Visible = true;
                lb_status.Text = "Updload Successful!!!!!";
            }
            else
            {
                lb_status.Visible = true;
                lb_status.Text = "Upload khong thanh cong!!!!!!!!!";
            }

            //txt_Node.Text = FileUpload1.PostedFile.FileName;

            ////A stream of bytes that represnts the binary file
            //FileStream fs = new FileStream(@"C:\Anh\"+filePath, FileMode.Open, FileAccess.Read);            
            ////The reader reads the binary data from the file stream
            //BinaryReader reader = new BinaryReader(fs);
            ////Bytes from the binary reader stored in BlobValue array
            //byte[] BlobValue = reader.ReadBytes((int)fs.Length);
            //string BlobFileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
            //fs.Close();
            //reader.Close();
            //SqlConnection DatabaseConn = new SqlConnection(@"Data Source=Bu\SQLEXPRESS;Initial Catalog=DMS_DEMO;Integrated Security=True");
            //SqlCommand SaveCommand = new SqlCommand();
            //SaveCommand.Connection = DatabaseConn;
            //SaveCommand.CommandType = CommandType.Text;
            //SaveCommand.CommandText = "INSERT INTO [DMS_Doc]([Name_Doc], [Doc],[ID_Folder])" +
            //    "VALUES (@FileName, @File,@Folder)";
            //SqlParameter FileNameParam = new SqlParameter("@FileName", SqlDbType.NVarChar);
            //SqlParameter FileParam = new SqlParameter("@File", SqlDbType.VarBinary);
            //SqlParameter FolderParam = new SqlParameter("@Folder", SqlDbType.Int);
            //SaveCommand.Parameters.Add(FileNameParam);
            //SaveCommand.Parameters.Add(FileParam);
            //SaveCommand.Parameters.Add(FolderParam);
            //FileNameParam.Value = filePath.Substring(filePath.LastIndexOf("\\") + 1);
            //FileParam.Value = BlobValue;
            //FolderParam.Value = Label1.Text;
            //try
            //{                
            //    SaveCommand.Connection.Open();
            //    SaveCommand.ExecuteNonQuery();

            //    lb_status.Visible = true;
            //    lb_status.Text = "Upload thành công!!!!!!!!";
            //}
            //catch
            //{
            //    lb_status.Visible = true;
            //    lb_status.Text = "Upload thất bại!!!!!!!!"; 
            //}
            //finally
            //{
            //    SaveCommand.Connection.Close();                
            //}
        }

        protected void lbtlogout_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = new HttpCookie("remember", "yes");
            cookie.Expires = DateTime.Now;
            Response.Cookies.Add(cookie);
            Response.Redirect("login.aspx");
        }
        int folder = 0;
        protected void show_file(string ten_file)
        {
            //string SavePath = @"C:\Anh\Down\";

            //SqlConnection SaveConn = new SqlConnection(
            // @"Data Source=Bu\SQLEXPRESS;Initial Catalog=DMS_DEMO;Integrated Security=True");

            //SqlCommand SaveCommand = new SqlCommand();
            //SaveCommand.CommandText =
            //    "Select Name_Doc, Doc from DMS_Doc where Name_Doc = @BlobFileName";
            //SaveCommand.Connection = SaveConn;

            //SaveCommand.Parameters.Add("@BlobFileName", SqlDbType.VarChar).Value = ten_file;

            ////the index number to write bytes to
            //long CurrentIndex = 0;

            ////the number of bytes to store in the array
            //int BufferSize = 100;

            ////The Number of bytes returned from GetBytes() method
            //long BytesReturned;

            ////A byte array to hold the buffer
            //byte[] Blob = new byte[BufferSize];

            //SaveCommand.Connection.Open();

            //SqlDataReader reader = SaveCommand.ExecuteReader(CommandBehavior.SequentialAccess);

            //while (reader.Read())
            //{
            //    FileStream fs = new FileStream(SavePath + "\\" + reader["Name_Doc"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);
            //    BinaryWriter writer = new BinaryWriter(fs);

            //    //reset the index to the beginning of the file
            //    CurrentIndex = 0;

            //    BytesReturned = reader.GetBytes(
            //        1, //the BlobsTable column index
            //        CurrentIndex, // the current index of the field from which to begin the read operation
            //        Blob, // Array name to write the buffer to
            //        0, // the start index of the array
            //        BufferSize // the maximum length to copy into the buffer
            //        );

            //    while (BytesReturned == BufferSize)
            //    {
            //        writer.Write(Blob);
            //        writer.Flush();

            //        CurrentIndex += BufferSize;
            //        BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);
            //    }

            //    writer.Write(Blob, 0, (int)BytesReturned);
            //    writer.Flush();
            //    writer.Close();

            //    fs.Close();

            string FilePath = Server.MapPath(@"~/Document/" + ten_file);
            FileInfo MyFileInfo = new FileInfo(FilePath);

            ReadTextFile r = new ReadTextFile(MyFileInfo);
            Editor1.Content = r.allText;

        }

        private void down(string filename)
        {
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
            //txt_Node.Text = Server.MapPath(@"~/Document/" + filename);
            Response.TransmitFile(Server.MapPath(@"~/Document/" + filename));
            Response.End();
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string currentCommand = e.CommandName;
            int currentRowIndex = Int32.Parse(e.CommandArgument.ToString());
            string idDoc = GridView1.DataKeys[currentRowIndex].Value.ToString();
            int ID = int.Parse(idDoc);
            string sql = "SELECT Name_Doc FROM DMS_Document WHERE ID_Doc = " + ID;
            SqlConnection SaveConn = new SqlConnection(
             @"Data Source=Bu\SQLEXPRESS;Initial Catalog=DMS_DEMO;Integrated Security=True");
            SaveConn.Open();
            SqlCommand cmd = new SqlCommand(sql, SaveConn);
            string name = (string)cmd.ExecuteScalar();
            if (currentCommand == "Download")
            {

                down(name);
                lb_status.Visible = true;
                lb_status.Text = "Download thành công!!!!!!!!";


                //string SavePath = @"C:\Users\Admin\Desktop\";
                //string sql = "Select Name_Doc, Doc from DMS_Doc where Name_Doc = '" + GridView1.DataKeys[currentRowIndex].Value.ToString() + "'";
                ////the index number to write bytes to
                //long CurrentIndex = 0;
                ////the number of bytes to store in the array
                //int BufferSize = 100;
                ////The Number of bytes returned from GetBytes() method
                //long BytesReturned;
                ////A byte array to hold the buffer
                //byte[] Blob = new byte[BufferSize];
                //SqlDataReader reader = da.executeReader(sql);
                //while (reader.Read())
                //{
                //    FileStream fs = new FileStream(SavePath  + reader["Name_Doc"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);
                //    BinaryWriter writer = new BinaryWriter(fs);
                //    //reset the index to the beginning of the file
                //    CurrentIndex = 0;
                //    BytesReturned = reader.GetBytes(
                //        1, //the BlobsTable column index
                //        CurrentIndex, // the current index of the field from which to begin the read operation
                //        Blob, // Array name to write the buffer to
                //        0, // the start index of the array
                //        BufferSize // the maximum length to copy into the buffer
                //        );
                //    while (BytesReturned == BufferSize)
                //    {
                //        writer.Write(Blob);
                //        writer.Flush();
                //        CurrentIndex += BufferSize;
                //        BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);
                //    }
                //    writer.Write(Blob, 0, (int)BytesReturned);
                //    writer.Flush(); writer.Close();
                //    fs.Close();
                //    lb_status.Visible = true;
                //    lb_status.Text = "Download thành công!!!!!!!!";
                //}
            }
            else if (currentCommand == "View")
            {
                lb_status.Visible = true;
                lb_status.Text = "You select command View!!!!!!!";
                Editor1.Visible = true;
                show_file(name);
            }
            else if (currentCommand == "xoa")
            {
                string sqlfolder = "DELETE FROM DMS_Folder_Doc WHERE ID_Doc = " + GridView1.DataKeys[currentRowIndex].Value.ToString();
                string sqldoc = "DELETE FROM DMS_Document WHERE ID_Doc = " + GridView1.DataKeys[currentRowIndex].Value.ToString();
                da.executeNonQuery(sqlfolder);
                da.executeNonQuery(sqldoc);
                show_doc(int.Parse(Label1.Text));
                lb_status.Visible = true;
                lb_status.Text = "Delete thành công!!!!!!!!";
            }
            else
            {
                lb_status.Visible = true;
                lb_status.Text = "Lỗi!!!!!!!!!!!!!";
            }


        }

        protected void GridView1_Sorted(object sender, EventArgs e)
        {

        }
        private string FuncSort(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;
            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;
                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }
            return newSortDirection;
        }
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dtTable = GridView1.DataSource as DataTable;
            if (dtTable != null)
            {
                DataView dtView = new DataView(dtTable);
                dtView.Sort = e.SortExpression + " " + FuncSort(e.SortDirection);
                GridView1.DataSource = dtView;
                GridView1.DataBind();
            }
        }
    }
}